/*
 * Teknei 2014 - All rights reserved
 */
package com.teknei.acabus.core.controller;

import java.io.IOException;
import java.io.Serializable;
import java.security.Principal;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.teknei.acabus.core.common.MessageConstants;

/**
 * Controller for Login
 * @author Jorge Amaro
 * @version 1.0
 * @since 1.0
 *
 */
@Named("login_controller")
@SessionScoped
public class LoginController extends GenericController implements Serializable {

	private String username;
	private int errorCounter;
	private static final Logger LOG = LoggerFactory
			.getLogger(LoginController.class);
	public static final String LOGOUT_OUTCOME = "logout";

	/**
	 * Validates login attributes
	 */
	public void validateLogin() {
		HttpServletRequest request = (HttpServletRequest) getFacesContext()
				.getExternalContext().getRequest();
		HttpSession session = request.getSession();
		String errorAttr = (String) session.getAttribute("error");
		if (errorAttr != null) {
			++errorCounter;
			//TODO check what to do when x number error occurr
			super.addErrorMessage(MessageConstants.MESSAGE_ERROR_LOGIN);
			session.removeAttribute("error");
		}
	}

	/**
	 * Logout the user and redirects
	 * @return
	 */
	public String logout() {
		HttpServletRequest request = (HttpServletRequest) getFacesContext()
				.getExternalContext().getRequest();
		HttpSession session = request.getSession();
		session.invalidate();
		getFacesContext().getExternalContext().invalidateSession();
		try {
			getFacesContext().getExternalContext()
					.redirect(request.getContextPath() + "/login/logout.jsp");
		} catch (IOException e) {
			return LOGOUT_OUTCOME;
		}
		return LOGOUT_OUTCOME;
	}

	/**
	 * Initialize the username of the logged user
	 */
	private void initUserName() {
		HttpServletRequest request = (HttpServletRequest) getFacesContext()
				.getExternalContext().getRequest();
		Principal principal = request.getUserPrincipal();
		username = principal.getName();
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		if (username == null || username.isEmpty()) {
			initUserName();
		}
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the errorCounter
	 */
	public int getErrorCounter() {
		return errorCounter;
	}

	/**
	 * @param errorCounter
	 *            the errorCounter to set
	 */
	public void setErrorCounter(int errorCounter) {
		this.errorCounter = errorCounter;
	}

}
